/**
 * Copyright (c) 2010 Simple Graph Tools contributors. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id$
 */
package org.sgt.transformations;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.sgt.coreutilities.ManageEMFResources;




/**
 * @author Anne BUTTIGHOFFER
 *
 */
public class DirtyLoader {
	
	@SuppressWarnings("unused")
	private ResourceSet resourceSet = null;
	
	private ManageEMFResources manageEMFResources = null;

	public DirtyLoader(){
		
		manageEMFResources = ManageEMFResources.getInstance();
		
        // Create a resource set to hold the resources.
    	resourceSet = ManageEMFResources.getResourceSet();
    			
	}
	
	private URI createEMFURI(IFile iFile){
		return	manageEMFResources.createURI(iFile);
	}
	
	private URI createEMFURI(File file){
		return	manageEMFResources.createURI(file);
	}

	public EList<EObject> loadRoots(IFile iFile, EClass eClass){
		URI emfURI = createEMFURI(iFile);
		return loadRoots(emfURI, eClass);
	}
		
	public EList<EObject> loadRoots(File file, EClass eClass){
		URI emfURI = createEMFURI(file);
		return loadRoots(emfURI, eClass);
	}
	
	public EList<EObject> loadRoots(URI emfURI, EClass eClass) {
		EList<EObject> results = new BasicEList<EObject>();
		@SuppressWarnings("unused")
		Resource resource = null;
		try {
			// Demand load resource for this file.

			resource = manageEMFResources.loadEMFResource(emfURI);
			Logger.log("Loaded " + emfURI);
		} catch (RuntimeException exception) {
			Logger.logError("Problem loading " + emfURI);
			exception.printStackTrace();
			return results;
		}

		if (eClass == null || eClass == EcorePackage.eINSTANCE.getEObject()) {
			 //wildCard for EObject (as it is not normally in superTypes).
			results = manageEMFResources.getAllRootNodes();

		} else {
			results = manageEMFResources.getRootNodesByEClass(eClass);
		}
		return results;
	}

}
